/**
 * 951. 翻转等价二叉树
 * https://leetcode-cn.com/problems/flip-equivalent-binary-trees/
 */
public class Solutions_951 {
    public static void main(String[] args) {
        TreeNode root1 = new TreeNode(1);
        root1.left = new TreeNode(2);
        root1.left.left = new TreeNode(4);
        root1.left.right = new TreeNode(5);
        root1.left.right.left = new TreeNode(7);
        root1.left.right.right = new TreeNode(8);
        root1.right = new TreeNode(3);
        root1.right.right = new TreeNode(6);

        TreeNode root2 = new TreeNode(1);
        root2.left = new TreeNode(3);
        root2.left.right = new TreeNode(6);
        root2.right = new TreeNode(2);
        root2.right.left = new TreeNode(4);
        root2.right.right = new TreeNode(5);
        root2.right.right.right = new TreeNode(7);
        root2.right.right.left = new TreeNode(8);  // output: true

        boolean result = flipEquiv(root1, root2);
        System.out.println(result);
    }

    public static boolean flipEquiv(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {
            return true;
        }
        if (root1 == null || root2 == null || root1.val != root2.val) {
            return false;
        }
        // (左左 || 左右) && (右右 || 右左)
        // 因为可以翻转，那么当左子树不等于左子树时，判断左子树是否等价于右子树
        // 最终要用 && 来连接，因为左子树要满足等价条件，右子树也要满足等价条件
        return (flipEquiv(root1.left, root2.left) || flipEquiv(root1.left, root2.right)) &&
                (flipEquiv(root1.right, root2.right) || flipEquiv(root1.right, root2.left));
    }
}
